package com.example.demo_lihe.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo_lihe.dao.WaterDataRepository;
import com.example.demo_lihe.entity.WaterData;
import com.example.demo_lihe.netty.NettyTcpClient;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class WaterDataService {
    @Autowired
    private WaterDataRepository tbWtDataRepository;

    @Autowired
    private NettyTcpClient nettyTcpClient;

    @Value("${njgn.appId}")
    private String appId;

    @Value("${njgn.appSecret}")
    private String appSecret;

    @Value("${njgn.get_access_token}")
    private String get_access_token;

    @Value("${njgn.select_sensor_point_by_project}")
    private String select_sensor_point_by_project;

    @Value("${njgn.select_many_point_last_data}")
    private String select_many_point_last_data;

    @Value("${njgn.projectId}")
    private String projectId;

    @Value("${njgn.sendPointId}")
    private Long sendPointId;

    private String token;

    @Scheduled(fixedRate = 10000)
    public void sendDataToTcpServer() {
        WaterData waterData = getLatestData();

        if (waterData != null) {

            nettyTcpClient.checkChannelAndConnect();

            try {
                // 将数据发送到TCP服务器的逻辑... led clearall
                //led clearall
                //led 24t 0 3 45 水位：
                //led 24t 0 2 18 降雨量：
                //led 24t 0 5 70 温度：
                String str = "led clearall \n" +
                        "led clearall \n" +
                        "led 24t 0 3 45 水位：" + String.format("%.2f", waterData.getStage()) + "\n" +
                        "led 24t 0 2 18 降雨量：\n" +
                        "led 24t 0 5 70 温度：\n";
                System.out.println("sendDataToTcpServer service sendMessage :" + str);
                nettyTcpClient.sendMessage(str);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        } else {
            System.out.println("sendDataToTcpServer service tbWtData = null");
        }


    }

    public WaterData getLatestData() {
        Optional<WaterData> latestDataOptional = tbWtDataRepository.findTopByPointIdOrderByTimeDesc(sendPointId);
        return latestDataOptional.orElse(null); // 如果结果为空，则返回 null
    }

    @Scheduled(cron = "0 0/30 * * * ?")
    public void getLastData() {
        if (StringUtil.isNullOrEmpty(token)) {
            token = getToken();
        }
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("projectId", projectId);

        String pointBody = HttpRequest.post(select_sensor_point_by_project)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("cookie", "generator=" + token)
                .form(requestParam)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        JSONObject pointsObject = JSONUtil.parseObj(pointBody);
        boolean op1 = (boolean) pointsObject.get("op");
        JSONArray pointsArray = pointsObject.getJSONArray("result");

        List<WaterData> waterDataList = new ArrayList<>();

        StringBuilder ids = new StringBuilder();
        ids.append("[");
        for (int i = 0; i < pointsArray.size(); i++) {
            JSONObject point = (JSONObject) pointsArray.get(i);
            ids.append((String) point.get("id"));
            if (i < pointsArray.size()) {
                ids.append(",");
            }

            WaterData waterData = new WaterData();
            waterData.setPointId(point.getLong("id"));
            waterData.setSensorId((String) point.get("sensorNumber"));
            waterData.setCgqbh((String) point.get("name"));
            waterDataList.add(waterData);
        }
        ids.append("]");
        Map<String, Object> requestParam2 = new HashMap<>();
        requestParam2.put("projectId", projectId);
        requestParam2.put("pointIds", ids.toString());
        //再根据所有的点位查询last数据
        String dataBody = HttpRequest.post(select_many_point_last_data)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("cookie", "generator=" + token)
                .form(requestParam2)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();

        JSONObject dataObject = JSONUtil.parseObj(dataBody);
        boolean op2 = (boolean) dataObject.get("op");
        JSONArray dataArray = dataObject.getJSONArray("result");

        List<WaterData> waterDataListSave = new ArrayList<>();
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject object = dataArray.getJSONObject(i);
            String pointId = object.getStr("pointId");
            WaterData waterData = null;

            JSONObject originalData = object.getJSONObject("originalData");
            Double ms = originalData.getDouble("温度");
            Double wd = originalData.getDouble("模数");
            JSONObject resultData = object.getJSONObject("resultData");
            Double stage = resultData.getDouble("水位高程");
            JSONObject paramData = object.getJSONObject("paramData");
            Double wdjzz = paramData.getDouble("温度基准值");

            Long id = object.getLong("id");
            Date time = object.getDate("time");

            for (WaterData waterData1 : waterDataList) {
                if (waterData1.getPointId().toString().equals(pointId)) {
                    waterData = waterData1;
                    break;
                }
            }

            if (waterData != null) {
                waterData.setId(id);
                waterData.setTime(time);
                waterData.setMs(ms);
                waterData.setWd(wd);
                waterData.setStage(stage);
                waterData.setWdjzz(wdjzz);
                waterDataListSave.add(waterData);
            }
        }

        tbWtDataRepository.saveAll(waterDataListSave);

    }

    public String getToken() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("appId", appId);
        requestParam.put("appSecret", appSecret);

        String result = HttpUtil.post(get_access_token, requestParam);
        JSONObject object = JSONUtil.parseObj(result);

        boolean op = (boolean) object.get("op");
        if (op) {
            System.out.println("getToken:result=" + object.get("result"));
            return (String) object.get("result");
        }
        return "";
    }

}
